package com.yytek.tcp.netty;

import cn.hutool.core.util.CharsetUtil;
import com.yytek.common.core.constant.CacheConstants;
import com.yytek.common.core.constant.ProtocolConstans;
import com.yytek.common.redis.service.RedisService;
import com.yytek.common.core.domain.DeviceConectInfo;
import com.yytek.gw.service.DriverMsgCommonService;
import com.yytek.gw.utils.DriverUtil;
import com.yytek.tcp.netty.tcp.NettyTcpServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * 接收消息handler处理
 */
@Slf4j
@Service
public class NettyServerHandler {

    @Value("${server.port}")
    private Integer serverPort;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DriverMsgCommonService driverMsgCommonService;


    public void read(ChannelHandlerContext context, ByteBuf byteBuf) throws Exception {
        log.info("{}->{}", context.channel().remoteAddress(), ByteBufUtil.hexDump(byteBuf));
        //TODO 判断设备类型,根据设备类型获取不同 规定获取设备id 协议格式
        String deviceId = byteBuf.toString(0, 22, CharsetUtil.CHARSET_ISO_8859_1);
        //如果不存在设备连接信息
        if(!NettyTcpServer.biDirectionHashMap.containsKey(deviceId)){
            //用于存储channel，然后配合write接口实现向下发送数据
            //缓存key设备id
            String key = CacheConstants.GW_DEVICE_CONECT_KEY+deviceId;
            DeviceConectInfo value = DriverUtil.getConectCacheValue(deviceId,serverPort, ProtocolConstans.TCP);
            redisService.setCacheObject(key,value);
            NettyTcpServer.biDirectionHashMap.put(deviceId, context.channel());
        }
        //TODO 读取业务处理
        //统一业务处理
        driverMsgCommonService.sendToCommonHandleMsg(deviceId,byteBuf);
    }
}
